package com.fingard.dsp.bank.directbank.zjtlcb02;

import java.io.File;
import java.sql.Connection;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

import com.alibaba.fastjson.JSON;
import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.db.JDBCHelper;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directConfig.TaskTimerSet;
import com.fingard.dsp.bank.directbank.bankInterface.IScheduleTask;
import com.fingard.io.FileHelper;
import com.fingard.net.FormSubmit;
import com.fingard.text.StringHelper;
import com.fingard.util.FtpUtil;
import com.fingard.util.SmbFileUtil;
import com.fingard.util.ZipHelper;

/**
 * Created by F on 2019/1/3.
 */
public class ZJTLCB02ScheduleTask extends ZJTLCB02Base implements IScheduleTask{

    private String receiptSaveToMainDir = "";

    private static final String INSERTRECEIPT = "INSERT INTO RECEIPTMAPPING(URID,BANK,OWNACT,BUSDATE,RECEIPTNO,RECEIPTFILE,CREATEDON) values (?,?,?,?,?,?,?);";

    @Override
    public void execTask(TaskTimerSet timerSet) {
        if (timerSet.taskNameList.toLowerCase().contains("tlcbreceipt")) {
            try {
                receiptSaveToMainDir = FGBiz.dspCenter.dspSet.receiptMainDir;
                if (!StringHelper.isNullOrEmpty(receiptSaveToMainDir)) {
                    if (!StringHelper.isNullOrEmpty(FGBiz.dspCenter.dspSet.receiptShareDir)) {
                        if (!StringHelper.isNullOrEmpty(FGBiz.dspCenter.dspSet.receiptPushServerUrl)) {
                            getStatement();
                        } else {
                            WriteBankLogLn("DSPSystem未配置回单文件推送地址");
                        }
                    } else {
                        WriteBankLogLn("DSPSystem未配置回单文件共享目录");
                    }
                } else {
                    WriteBankLogLn("DSPSystem未配置回单文件下载保存主目录");
                }
            } catch (Exception e) {
                WriteBankLogLn(e);
            }
        }
    }

    private void getStatement() throws Exception{
        String uploadType=SmbFileUtil.getUploadType();
        Connection conn= null;
        try {
            conn  = FGBiz.getLocalDbConn();
            //获取记录的数据，记录的数据根据帐号进行文件夹整理
            String path = FGBiz.dspCenter.dspSet.dataDirPath + File.separator + "datafile" + File.separator + bankFront.code + File.separator + "cltRefNoFile" + File.separator;
            File file = new File(path);
            File[] tempList = file.listFiles();
            WriteBankLogLn("1.1下载回单文件start");
            if (tempList == null || tempList.length == 0) {
                WriteBankLogLn("文件夹没有需要下载电子回单的账户文件夹" + path);
                return;
            }
            WriteBankLogLn("1.2存在回单记录，开始请求下载");
            int tmpFileCount=0;//统计上传成功文件数
            StringBuilder json = new StringBuilder();//推送到ats的数据字符串
            json.append("transType=downloadreceipt&data={\"rows\":[");
            //记录成功处理回单文件的名称
            StringBuilder sb2 = new StringBuilder();
            //解析所有数据
            for(File files:tempList){
                String fileContent="";
                if (FileHelper.existFile(files.getPath())) {
                    fileContent = FtpUtil.getTextFromFile(files.getPath(), getCharset());
                }
                String[] content=fileContent.replaceAll("\r","").replaceAll("\n","").split("\\|");
                if(content.length==5){
                    //从ftp服务器上下载文件
                    FtpSet ftpSet = bankFront.getFtpSet("receipt");
                    String localReceiptPath=receiptSaveToMainDir+File.separator+"TLCB02"+File.separator+Format.Date8Format.format(new Date());
                    if(!FileHelper.existFile(localReceiptPath)){
                        FileHelper.mkdir(localReceiptPath);
                    }
                    //下载文件
                    downFromFtp(localReceiptPath,ftpSet,content[1]);
                    //本地回单zip文件存放位置
                    String localPath=localReceiptPath+File.separator+content[1];
                    //文件路径的zip文件存在，开始解压
                    if(FileHelper.existFile(localPath)){
                        WriteBankLogLn("1.3文件"+localPath+"存在，开始解压");
                        //本地存放回单目录
                        String localFilePath=FGBiz.dspCenter.dspSet.dataDirPath + File.separator + "datafile" + File.separator + bankFront.code
                                + File.separator + "receiptDataFile" + File.separator + content[2].trim();
                        if(!FileHelper.existFile(localFilePath)){
                            FileHelper.mkdir(localFilePath);
                        }
                        //解压
                        ZipHelper.unzipFile(localPath, localFilePath);
                        WriteBankLogLn("1.4解压"+localPath+"到目录"+localFilePath);
                        File receiptDir = new File(localFilePath + File.separator + content[1].replace(".zip", ""));
                        if (!receiptDir.exists()) {
                            WriteBankLogLn("不存在回单目录:" + receiptDir.getName());
                            continue;
                        }
                        //获取解压后的文件
                        File[] receiptFiles = receiptDir.listFiles();
                        if (receiptFiles != null && receiptFiles.length > 0) {
                            WriteBankLogLn(files.getName() + "1.5解压后共有" + receiptFiles.length + "个文件");
                            //循环处理解压后的文件：上传至共享目录，拼接返回ATS的字符串信息
                            for (File receiptFile : receiptFiles) {
                                String tmpByDate = Format.Date8Format.format(new Date());
                                tmpByDate = tmpByDate.substring(0, 6) + "/" + tmpByDate.substring(6, 8) + "/" + reqHeader.bankCode + "/" + content[2] + "/";
                                //tranDate = receiptFile.getName().substring(0, 8);//获取回单日期
                                //上传文件到共享目录下
                                int result = -1;

                                if (receiptFile.exists()) {
                                   if("smb".equals(uploadType)) {
                                       WriteBankLogLn("1.6正在上传文件至共享目录:" + FGBiz.dspCenter.dspSet.receiptShareDir);
                                       result = SmbFileUtil.smbUploading(receiptFile.getPath(), tmpByDate, FGBiz.dspCenter.dspSet.receiptShareDir);
                                   } else{
                                        tmpByDate =tmpByDate.replaceAll(reqHeader.bankCode + "/","");
                                        WriteBankLogLn("正在上传文件至微服务:" + FGBiz.dspCenter.dspSet.receiptShareDir);
                                        Map<String,String> map = FormSubmit.fileUpload
                                                (FGBiz.dspCenter.dspSet.receiptShareDir, content[2].trim(),receiptFile.getPath(),tmpByDate,receiptFile.getName(),getCharset());
                                       WriteBankLogStep3(JSON.toJSONString(map));
                                        if(map.keySet().size()!=0){
                                            result = Integer.valueOf(map.get("respCode"));
                                            tmpByDate =map.get("remotePath");
                                        }else{
                                            result = -1;
                                        }
                                    }
                                }
                                //上传成功处理
                                if (result == 0 || result == 1) {
                                    tmpFileCount++;
                                    if (result == 0) {
                                        WriteBankLogLn("1.7文件上传成功");
                                    }else {
                                        WriteBankLogLn("1.7文件已存在共享目录无需重复上传");
                                    }
                                    //推送数据给ATS处理
                                    json.append("{");
                                    json.append("\"actNum\":\"" + content[2].trim() + "\",");
                                    json.append("\"actCur\":\""+ content[3].trim() +"\",");
                                    json.append("\"receiptCode\":\"" + content[0].trim() + "\",");//回单编号
                                    json.append("\"receiptType\":\"" + "" + "\",");//回单类型  1：存款回单；2：取款回单；3：转账回单；4：缴税回单；5：收费回单；6定期回单；7：活期回单
                                    json.append("\"receiptState\":\"" + "" + "\",");//回单状态 1：正常；2：冲正；3：被冲正；4：当日冲正
                                    json.append("\"oppActName\":\"" + "" + "\",");
                                    json.append("\"oppActNum\":\"" + "" + "\",");
                                    json.append("\"amount\":\"" + "" + "\",");
                                    json.append("\"moneyway\":\"" + "" + "\",");
                                    json.append("\"tranSeqNo\":\"" + reqHeader.transSeqID + "\",");
                                    json.append("\"tranCode\":\"" + "" + "\",");//交易码?
                                    json.append("\"tranDate\":\"" + Format.Date10Format.format(Format.Date8Format.parse(content[4].trim())) + "\",");
                                    if("smb".equals(uploadType)) {
                                        json.append("\"filePath\":\"" + tmpByDate + receiptFile.getName() + "\",");//回单文件仓库存储路径
                                    }else{
                                        json.append("\"filePath\":\"" + tmpByDate + "\",");//文件路径
                                    }
                                    json.append("\"fileType\":\"1\"");
                                    json.append("},");
                                    //文件处理完毕，删除临时文件
                                    if (FileHelper.deleteFileIfExists(files.getPath())) {
                                        WriteBankLogLn("1.8删除临时文件：" + files.getPath());
                                    }
                                    sb2.append(files.getName()+",");
                                    //记录已推送的电子回单
                                    JDBCHelper.update(conn, INSERTRECEIPT, new Object[]{UUID.randomUUID().toString(), reqHeader.bankCode, content[2].trim(), content[4].trim().replace("-", ""), content[0].trim(), receiptFile.getPath(), new Date()});

                                    /*String reqNoFile=FGBiz.dspCenter.dspSet.dataDirPath + File.separator + "datafile" + File.separator + bankFront.code
                                            + File.separator + "receiptSuccessId";
                                    if(!FileHelper.existFile(reqNoFile)){
                                        FileHelper.mkdir(reqNoFile);
                                    }
                                    FileHelper.writeFile(reqNoFile+ File.separator + content[0].trim()+".txt", "0", getCharset());*/
                                } else {
                                    WriteBankLogLn("1.7上传文件至共享目录失败，请检查共享目录配置是否正确");
                                    continue;
                                }
                            }
                        }
                    }else {
                        WriteBankLogLn("1.3文件路径"+content[1].trim()+"的zip文件暂不存在，等待银行推送");
                    }
                }else {
                    WriteBankLogLn("数据丢失");
                }
            }
            WriteBankLogLn("成功保存了" + tmpFileCount + "个文件,文件名为："+sb2);
            if (tmpFileCount > 0) {
                json.deleteCharAt(json.length() - 1);
                json.append("]}");

                String[] data ;
                String receiptPushType = FGBiz.dspCenter.dspSet.receiptPushType;
                if("nbGateway".equals(receiptPushType)) {
                    WriteBankLogLn("3.推送给网关的数据" + json.toString());
                    data= FormSubmit.receiptInfoSend(json.toString(),this);
                    if (data[0].length() == 0 && data[1].equals("ok")) {
                        WriteBankLogLn("推送数据到网关成功,请查看数据");
                    } else {
                        WriteBankLogLn("推送数据到网关失败");
                    }
                }else{
                    WriteBankLogLn("3.推送给ATS的数据" + json.toString());
                    data = sendToATS(json.toString());
                    if (data[0].length() == 0 && data[1].equals("ok")) {
                        WriteBankLogLn("推送数据到ATS成功,请查看数据");
                    } else {
                        WriteBankLogLn("推送数据到ATS失败");
                    }
                }
            } else {
                WriteBankLogLn("成功保存文件条数为0，不需要推送数据到ATS");
            }
        }catch (Exception e){
            WriteBankLogLn(e);
        }finally {
            conn.close();
        }
    }
}
